package com.moyu.admin.web;

import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@Slf4j
public class LoginController {

  @RequestMapping("/login")
  public String login(HttpServletRequest request) {
    log.info("==login==");
    if (request.getMethod().equals(HttpMethod.GET)) {
      return "login";
    } else if (request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
      String username = request.getParameter("username");
      String password = request.getParameter("password");
      UsernamePasswordToken token = new UsernamePasswordToken(username, password);
      try {
        SecurityUtils.getSubject().login(token);
        return "redirect:/";
      } catch (AuthenticationException e) {
        log.error("登录失败: " , e);
        return "login";
      }
    }
    return "login";
  }
}

